package itsm.isperp.module.service.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataRequest;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.domain.IBean;
import itsm.isperp.framework.service.UploadFileService;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppUploadFile;
import itsm.isperp.module.repository.app.AppUploadFileMapper;
import itsm.isperp.module.repository.solr.SolrKngKnowledgeItemRepository;

import java.util.List;

import javax.persistence.Table;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

/**
 * 系统上传文件服务
 * 
 * @author lizx
 * @date 2013-3-14
 */
@Service
public class AppUploadFileService extends UploadFileService<AppUploadFile> {

	@Autowired
	protected AppUploadFileMapper appUploadFileMapper;

	@Override
	public AppUploadFileMapper getRepository() {
		return this.appUploadFileMapper;
	}

	public ResultMessage delete(String id) {
		super.delete(id);
		SolrKngKnowledgeItemRepository solrKngKnowledgeItemRepository = ContextHolder
				.getSpringBean("solrKngKnowledgeItemRepository");

		solrKngKnowledgeItemRepository.delete(id);

		return ResultMessage.success();

	}

	public void deleteBySourceId(String sourceId) {
		this.getRepository().deleteBySourceId(sourceId);
	}

	public AppUploadFile getOneBySourceId(String sourceId, String... columns) {
		JqGridRequest req = new JqGridRequest();
		req.setSelectColumns(columns);
		req.isPageable(false).addFilterRule("source_id", JqGridFilterRuleOp.eq,
				sourceId);

		DataResponse<AppUploadFile> results = this.getRepository()
				.findAllByRequest(req);

		if (results != null && results.size() == 1)
			return results.get(0);
		return null;
	}

	public DataResponse<AppUploadFile> getBySourceId(String sourceId) {
		DataRequest req = new JqGridRequest();

		return this.getRepository()
				.findAllByRequest(
						req.isPageable(false)
								.addFilterRule("source_id",
										JqGridFilterRuleOp.eq, sourceId)
								.setSort("modify_date", Direction.ASC));

	}

	public List<AppUploadFile> findBySource(Class<? extends IBean> clazz,
			String condition) {

		String tableName = clazz.getAnnotation(Table.class).name();

		if (StringUtils.isEmpty(condition)) {

			return appUploadFileMapper.findBySource(tableName, "1=1");
		} else {

			return appUploadFileMapper.findBySource(tableName, condition);
		}

	}
}
